package net.chenlin.dp.modules.task;

import lombok.extern.slf4j.Slf4j;
import net.chenlin.dp.modules.business.dao.DeviceRegisterMapper;
import net.chenlin.dp.modules.business.entity.vo.deviceRegister.DeviceRegisterStatusVo;
import net.chenlin.dp.modules.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Yangsm
 * @ClassName: DeviceStatusTask
 * @Description: 定时任务查看心跳连接是否断开
 * @date 2023年01月31日 20:25
 */
@Slf4j
@Component
public class DeviceStatusTask {

    @Autowired
    private DeviceRegisterMapper deviceRegisterMapper;

    @Transactional(rollbackFor = Exception.class)
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void updateDeviceStatus() throws Exception {

        log.info("定时任务查看心跳连接是否断开");

        // 获取
        List<DeviceRegisterStatusVo> list = deviceRegisterMapper.getAllDeviceStatusInfo();
        if(list.size() != 0){
            list.stream().forEach( vo -> {
                Date heartbeatTime = vo.getHeartbeatTime();
                if(heartbeatTime != null){
                    Date now = new Date();

                    //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Calendar beforeTime = Calendar.getInstance();
                    beforeTime.add(Calendar.MINUTE, -6);// 3分钟之前的时间
                    Date beforeD = beforeTime.getTime();
                    boolean effectiveDate = DateUtils.isEffectiveDate(heartbeatTime, beforeD, now);
                    if(!effectiveDate && vo.getDeviceStatus() == 0){
                        // 改为离线状态
                        deviceRegisterMapper.updateDeviceLineStatus(vo.getDeviceNo());
                    }
                    // 恢复在线状态
                    if(effectiveDate && vo.getDeviceStatus() == 1){
                        deviceRegisterMapper.recoveryDeviceLineStatus(vo.getDeviceNo());
                    }
                }
                if(null == heartbeatTime){
                    deviceRegisterMapper.updateDeviceStatus(vo.getDeviceNo());
                }
            });
        }
        log.info("updateDeviceStatus ==== 定时任务结束、、、、");
    }

}
